import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col, Select, Table, Empty } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, ReadOutlined, ExclamationCircleOutlined, CheckCircleOutlined, SendOutlined, UserAddOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'

// 模拟数据
const mockDepartments = [
    { id: 1, name: '人力资源部' },
    { id: 2, name: '技术部' },
    { id: 3, name: '市场部' },
    { id: 4, name: '财务部' }
]

// 模拟员工数据
const mockEmployees = [
    {
        id: 1,
        name: '张三',
        departmentId: 1,
        position: '人力资源专员',
        email: 'zhangsan@example.com',
        phone: '13800000001'
    },
    {
        id: 2,
        name: '李四',
        departmentId: 2,
        position: '高级工程师',
        email: 'lisi@example.com',
        phone: '13800000002'
    }
]

const mockTrainings = [
    {
        id: 1,
        title: '新员工入职培训',
        description: '帮助新员工了解公司文化和工作流程',
        trainer: '张三',
        departmentId: 1,
        startDate: '2024-01-15',
        endDate: '2024-01-16',
        location: '培训室A',
        status: '进行中',
        max_participants: 30,
        current_participants: 20,
        participants: [mockEmployees[0], mockEmployees[1]]
    },
    {
        id: 2,
        title: '技术架构培训',
        description: '介绍公司技术架构和最佳实践',
        trainer: '李四',
        departmentId: 2,
        startDate: '2024-02-01',
        endDate: '2024-02-02',
        location: '会议室B',
        status: '计划中',
        max_participants: 20,
        current_participants: 5,
        participants: [mockEmployees[1]]
    },
    {
        id: 3,
        title: '领导力培训',
        description: '提升管理者的领导能力',
        trainer: '王五',
        departmentId: 1,
        startDate: '2024-01-10',
        endDate: '2024-01-12',
        location: '培训中心',
        status: '已完成',
        max_participants: 15,
        current_participants: 15,
        participants: [mockEmployees[0]]
    }
]

const { confirm } = Modal

const Training = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentTraining, setCurrentTraining] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewTraining, setViewTraining] = useState(null)
    const [departments, setDepartments] = useState([])
    const [searchKeyword, setSearchKeyword] = useState('')

    useEffect(() => {
        fetchTrainings()
        fetchDepartments()
    }, [pagination.current, pagination.pageSize, searchKeyword])
    
    // 获取部门列表（使用模拟数据）
    const fetchDepartments = () => {
        setDepartments(mockDepartments)
    }

    // 获取培训数据（使用模拟数据）
    const fetchTrainings = () => {
        setLoading(true)
        try {
            const start = (pagination.current - 1) * pagination.pageSize
            const end = start + pagination.pageSize
            
            // 根据关键字筛选数据
            const filteredData = mockTrainings.filter(item => {
                if (!searchKeyword) return true
                return (
                    item.title.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                    item.trainer.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                    mockDepartments.find(d => d.id === item.departmentId)?.name.toLowerCase().includes(searchKeyword.toLowerCase())
                )
            })

            const paginatedData = filteredData.slice(start, end)
            setDataSource(paginatedData)
            setPagination({
                ...pagination,
                total: filteredData.length
            })
        } catch (error) {
            console.error('获取培训列表失败:', error)
            message.error('获取培训列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = (value) => {
        setSearchKeyword(value)
    }

    // 添加培训
    const handleAdd = () => {
        setCurrentTraining(null)
        setVisible(true)
    }

    // 编辑培训（使用模拟数据）
    const handleEdit = (record) => {
        setCurrentTraining(record)
        setVisible(true)
    }

    // 查看培训详情（使用模拟数据）
    const handleView = (record) => {
        setViewTraining(record)
        setViewVisible(true)
    }

    // 删除培训（使用模拟数据）
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这个培训项目吗？此操作不可恢复。',
            onOk: () => {
                try {
                    setLoading(true)
                    // 模拟删除操作
                    const index = mockTrainings.findIndex(item => item.id === id)
                    if (index > -1) {
                        mockTrainings.splice(index, 1)
                    }
                    message.success('删除成功')
                    // 重新获取列表数据
                    fetchTrainings()
                } catch (error) {
                    console.error('删除培训失败:', error)
                    message.error('删除培训失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 发布培训（使用模拟数据）
    const handlePublish = (id) => {
        confirm({
            title: '确认发布',
            icon: <SendOutlined />,
            content: '确定要发布这个培训项目吗？发布后状态将变为进行中。',
            onOk: () => {
                try {
                    setLoading(true)
                    // 模拟发布操作
                    const training = mockTrainings.find(item => item.id === id)
                    if (training) {
                        training.status = '进行中'
                    }
                    message.success('发布成功')
                    // 重新获取列表数据
                    fetchTrainings()
                } catch (error) {
                    console.error('发布培训失败:', error)
                    message.error('发布培训失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 完成培训（使用模拟数据）
    const handleComplete = (id) => {
        confirm({
            title: '确认完成',
            icon: <CheckCircleOutlined />,
            content: '确定要将这个培训项目标记为已完成吗？',
            onOk: () => {
                try {
                    setLoading(true)
                    // 模拟完成操作
                    const training = mockTrainings.find(item => item.id === id)
                    if (training) {
                        training.status = '已完成'
                    }
                    message.success('培训已标记为完成')
                    // 重新获取列表数据
                    fetchTrainings()
                } catch (error) {
                    console.error('完成培训失败:', error)
                    message.error('完成培训失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 报名培训（使用模拟数据）
    const handleEnroll = (id) => {
        try {
            setLoading(true)
            // 模拟报名操作
            const training = mockTrainings.find(item => item.id === id)
            if (training && training.current_participants < training.max_participants) {
                training.current_participants += 1
                message.success('报名成功')
                // 重新获取列表数据
                fetchTrainings()
                // 如果当前正在查看该培训，更新查看的培训信息
                if (viewTraining && viewTraining.id === id) {
                    setViewTraining({...training})
                }
            } else {
                message.error('培训名额已满')
            }
        } catch (error) {
            console.error('报名培训失败:', error)
            message.error('报名培训失败')
        } finally {
            setLoading(false)
        }
    }

    // 表单提交（使用模拟数据）
    const handleFormSubmit = (values) => {
        try {
            setLoading(true)
            if (currentTraining) {
                // 编辑培训
                const index = mockTrainings.findIndex(item => item.id === currentTraining.id)
                if (index > -1) {
                    mockTrainings[index] = {
                        ...mockTrainings[index],
                        ...values
                    }
                }
                message.success('编辑成功')
            } else {
                // 添加培训
                const newTraining = {
                    ...values,
                    id: mockTrainings.length + 1,
                    current_participants: 0
                }
                mockTrainings.push(newTraining)
                message.success('添加成功')
            }
            // 关闭模态框
            setVisible(false)
            // 重新获取列表数据
            fetchTrainings()
        } catch (error) {
            console.error('保存培训失败:', error)
            message.error('保存培训失败')
        } finally {
            setLoading(false)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '培训名称',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '培训讲师',
            dataIndex: 'trainer',
            key: 'trainer'
        },
        {
            title: '所属部门',
            dataIndex: 'departmentId',
            key: 'departmentId',
            render: (departmentId) => {
                const dept = departments.find(d => d.id === departmentId);
                return dept ? dept.name : '-';
            }
        },
        {
            title: '开始日期',
            dataIndex: 'startDate',
            key: 'startDate'
        },
        {
            title: '结束日期',
            dataIndex: 'endDate',
            key: 'endDate'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = 'blue'
                if (text === '已完成') color = 'green'
                if (text === '计划中') color = 'orange'
                if (text === '进行中') color = 'blue'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '参与人数',
            key: 'participants',
            render: (_, record) => (
                <span>{record.current_participants || 0}/{record.max_participants || 0}</span>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 300,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    {record.status === '计划中' && (
                        <Button 
                            type="text" 
                            icon={<SendOutlined />} 
                            onClick={() => handlePublish(record.id)}
                        >
                            发布
                        </Button>
                    )}
                    {record.status === '进行中' && (
                        <Button 
                            type="text" 
                            icon={<CheckCircleOutlined />} 
                            onClick={() => handleComplete(record.id)}
                        >
                            完成
                        </Button>
                    )}
                    {(record.status === '计划中' || record.status === '进行中') && 
                     record.currentParticipants < record.maxParticipants && (
                        <Button 
                            type="text" 
                            icon={<UserAddOutlined />} 
                            onClick={() => handleEnroll(record.id)}
                        >
                            报名
                        </Button>
                    )}
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="training-container">
            <Card title="培训管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加培训
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchTrainings}
                    searchPlaceholder="搜索培训名称/讲师/部门"
                />
            </Card>

            {/* 培训表单模态框 */}
            <Modal
                title={currentTraining ? '编辑培训' : '添加培训'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentTraining}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="title"
                        label="培训名称"
                        rules={[{ required: true, message: '请输入培训名称' }]}
                    >
                        <input placeholder="请输入培训名称" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="培训描述"
                        rules={[{ required: true, message: '请输入培训描述' }]}
                    >
                        <textarea placeholder="请输入培训描述" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="trainer"
                        label="培训讲师"
                        rules={[{ required: true, message: '请输入培训讲师' }]}
                    >
                        <input placeholder="请输入培训讲师" />
                    </Form.Item>
                    <Form.Item
                        name="departmentId"
                        label="所属部门"
                        rules={[{ required: true, message: '请选择所属部门' }]}
                    >
                        <Select placeholder="请选择部门">
                            {departments.map(dept => (
                                <Select.Option key={dept.id} value={dept.id}>
                                    {dept.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="startDate"
                        label="开始日期"
                        rules={[{ required: true, message: '请选择开始日期' }]}
                    >
                        <input type="date" />
                    </Form.Item>
                    <Form.Item
                        name="endDate"
                        label="结束日期"
                        rules={[{ required: true, message: '请选择结束日期' }]}
                    >
                        <input type="date" />
                    </Form.Item>
                    <Form.Item
                        name="location"
                        label="培训地点"
                        rules={[{ required: true, message: '请输入培训地点' }]}
                    >
                        <input placeholder="请输入培训地点" />
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="计划中">计划中</option>
                            <option value="进行中">进行中</option>
                            <option value="已完成">已完成</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="max_participants"
                        label="最大人数"
                        rules={[{ required: true, message: '请输入最大参与人数' }]}
                    >
                        <input type="number" placeholder="请输入最大参与人数" />
                    </Form.Item>
                    <Form.Item
                        name="current_participants"
                        label="当前人数"
                        rules={[{ required: true, message: '请输入当前参与人数' }]}
                    >
                        <input type="number" placeholder="请输入当前参与人数" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 培训详情模态框 */}
            <Modal
                title="培训详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={
                    viewTraining && (
                        <div>
                            {viewTraining.status === '计划中' && (
                                <Button 
                                    type="primary" 
                                    icon={<SendOutlined />} 
                                    onClick={() => {
                                        handlePublish(viewTraining.id);
                                        setViewVisible(false);
                                    }}
                                >
                                    发布培训
                                </Button>
                            )}
                            {viewTraining.status === '进行中' && (
                                <Button 
                                    type="primary" 
                                    icon={<CheckCircleOutlined />} 
                                    onClick={() => {
                                        handleComplete(viewTraining.id);
                                        setViewVisible(false);
                                    }}
                                >
                                    完成培训
                                </Button>
                            )}
                            <Button onClick={() => setViewVisible(false)}>关闭</Button>
                        </div>
                    )
                }
                width={700}
            >
                {viewTraining && (
                    <div className="training-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="基本信息" key="1">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewTraining.id}</Descriptions.Item>
                                            <Descriptions.Item label="培训名称">{viewTraining.title}</Descriptions.Item>
                                            <Descriptions.Item label="培训讲师">{viewTraining.trainer}</Descriptions.Item>
                                            <Descriptions.Item label="所属部门">
                                                {departments.find(d => d.id === viewTraining.departmentId)?.name || '-'}
                                            </Descriptions.Item>
                                            <Descriptions.Item label="开始日期">{viewTraining.startDate}</Descriptions.Item>
                                            <Descriptions.Item label="结束日期">{viewTraining.endDate}</Descriptions.Item>
                                            <Descriptions.Item label="培训地点">{viewTraining.location}</Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={viewTraining.status === '已完成' ? 'green' : (viewTraining.status === '计划中' ? 'orange' : 'blue')}>
                                                    {viewTraining.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="参与人数">{viewTraining.currentParticipants}/{viewTraining.maxParticipants}</Descriptions.Item>
                                            <Descriptions.Item label="描述" span={2}>{viewTraining.description}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="参与人员" key="2">
                                        {viewTraining.participants && viewTraining.participants.length > 0 ? (
                                            <Table 
                                                dataSource={viewTraining.participants} 
                                                rowKey="id"
                                                pagination={false}
                                                columns={[
                                                    {
                                                        title: 'ID',
                                                        dataIndex: 'id',
                                                        key: 'id',
                                                        width: 80
                                                    },
                                                    {
                                                        title: '姓名',
                                                        dataIndex: 'name',
                                                        key: 'name'
                                                    },
                                                    {
                                                        title: '部门',
                                                        dataIndex: 'department',
                                                        key: 'department'
                                                    },
                                                    {
                                                        title: '报名时间',
                                                        dataIndex: 'enrollTime',
                                                        key: 'enrollTime'
                                                    },
                                                    {
                                                        title: '状态',
                                                        dataIndex: 'status',
                                                        key: 'status',
                                                        render: (text) => (
                                                            <Tag color={text === '已完成' ? 'green' : 'blue'}>{text}</Tag>
                                                        )
                                                    }
                                                ]}
                                            />
                                        ) : (
                                            <Empty description="暂无参与人员" />
                                        )}
                                        {viewTraining.status !== '已完成' && (
                                            <div style={{ marginTop: 16, textAlign: 'center' }}>
                                                <Button 
                                                    type="primary" 
                                                    icon={<UserAddOutlined />} 
                                                    onClick={() => handleEnroll(viewTraining.id)}
                                                    disabled={viewTraining.currentParticipants >= viewTraining.maxParticipants}
                                                >
                                                    报名参加
                                                </Button>
                                                {viewTraining.currentParticipants >= viewTraining.maxParticipants && (
                                                    <p style={{ color: 'red', marginTop: 8 }}>该培训已达到最大参与人数</p>
                                                )}
                                            </div>
                                        )}
                                    </Tabs.TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

export default Training